package com.woniu.car.controller;


import com.woniu.car.common.JWTUtil;
import com.woniu.car.common.ResponseEntity;
import com.woniu.car.parameter.AddCartsParam;
import com.woniu.car.parameter.DeleteCartsParam;
import com.woniu.car.parameter.UpdateParam;
import com.woniu.car.service.TCartsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author zhoubinbin
 * @since 2021-06-21
 */
@RestController
@RequestMapping("/tCarts")
@Api(tags = "用户购物车")
public class TCartsController {
    @Resource
    private TCartsService cartsService;
    //查询购物车
    @GetMapping("selectCarts")
    public ResponseEntity selectCarts(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token==null){
            return new ResponseEntity(500,"您当前未登陆,请登陆后进行操作",null);
        }
        String id = JWTUtil.getId(token);
        Integer userId = Integer.valueOf(id);
        return cartsService.selectCarts(userId);
    }
    //删除购物车中的商品，可以删除多个,参数购物车id数组
    @ApiOperation(value = "删除购物车中一个或多个商品")
    @DeleteMapping("deleteCarts")
    public ResponseEntity deleteCarts(@RequestBody DeleteCartsParam deleteCartsParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token==null){
            return new ResponseEntity(500,"您当前未登陆,请登陆后进行操作",null);
        }
        String id = JWTUtil.getId(token);
        Integer userId = Integer.valueOf(id);
        return cartsService.deleteCarts(deleteCartsParam,userId);
    }
    //修改购物车,数量
    @ApiOperation(value = "修改购物车商品数量可以修改多个商品数量")
    @PutMapping("updateCarts")
    public ResponseEntity updateCarts(@RequestBody UpdateParam updateParam, HttpServletRequest request){

        return cartsService.updateCarts(updateParam);
    }
    //新增购物车
    @ApiOperation(value = "新增购物车")
    @PostMapping("addCarts")
    public ResponseEntity addCarts(@Valid @RequestBody AddCartsParam addCartsParam, BindingResult bindingResult, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token==null){
            return new ResponseEntity(500,"您当前未登陆,请登陆后进行操作",null);
        }
        String id = JWTUtil.getId(token);
        Integer userId = Integer.valueOf(id);
        for (ObjectError error : bindingResult.getAllErrors()) {
            return new ResponseEntity(500,"参数错误",error.getDefaultMessage());
        }
        return cartsService.addCarts(addCartsParam,userId);
    }
}

